# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     ：skyTree
# version    ：python 3.11
# Description：自定义响应类型
"""
from rest_framework.renderers import JSONRenderer


class MyJSONRenderer(JSONRenderer):
    # 重构render方法
    def render(self, data, accepted_media_type=None, renderer_context=None):
        response = renderer_context['response']
        status_code_number = renderer_context['response'].status_code
        # 封装信息
        if isinstance(data, dict):
            msg = data.pop('msg', '操作成功!')
            code = data.pop('code', status_code_number)
        else:
            msg = '操作成功！'
            code = 200
        # 处理 204 状态码，将其更改为 200 并设置适当的响应数据
        if status_code_number == 204:
            response.status_code = 200
            if not data:
                data = None
        ret = {'data': data, 'code': code, 'msg': msg}
        return super().render(ret, accepted_media_type, renderer_context)
